

public class problems25 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 对于链表反转的题目，我们确定几条规则
     * 每次都先加一个哨兵元素dummy(0,next)
     * p0作为反转链表的前面一个元素
     * 每一轮的反转 从 cur=p0.next和pre=null开始
     * ListNode nxt = cur.next;
     * cur.next = pre;
     * pre = cur;
     * cur = nxt;
     * count++;
     * 每一轮的反转结束需要给已经断掉的部分连上
     * ，以及确定新的p0的位置
     * p0.next.next = cur;
     * ListNode t = p0.next;
     * p0.next = pre;
     * p0 = t;
     */

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head);
        //先计数
        int totalNodeCount = 0;
        ListNode cur = dummy;
        while (cur.next != null) {
            totalNodeCount++;
            cur = cur.next;
        }

        ListNode p0 = dummy;
        ListNode pre = null;
        while (totalNodeCount >= k) {
            pre = null;
            cur = p0.next;

            int count = 0;
            while (count < k) {
                ListNode nxt = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nxt;
                count++;
            }
            p0.next.next = cur;
            ListNode t = p0.next;
            p0.next = pre;
            p0 = t;

            totalNodeCount -= k;
        }

        return dummy.next;
    }
}
